#include "messaging.h"
#include <legacymsp430.h>

static uint8_t mStringIndex = 0;
static MessageState_e mMessageState = COMMAND_STRING0;
const char COMMAND_STRING[5] = "cmd: ";
const char DOOR_CMD_STRING[13] = "trigger door\n";
const char STATUS_REQ_STRING[15] = "request status\n";

static void HandleDoorCmd();
static int HandleStatusReq();
static void delay_loop();

int ProcessByte(char data)
{
   int ret_status = RET_ERR_NONE;
   //P1OUT = 0x01;   //Turn on led temporary check
   switch(mMessageState)
   {
      case COMMAND_STRING0:
      {
         if(data != COMMAND_STRING[mStringIndex])
            mStringIndex = 0;
         else
            ++mStringIndex;
         
         if(mStringIndex == 5) //check for first character
         {
            mStringIndex = 0;
            mMessageState = COMMAND_STRING1;
         }
         
         break;
      }
      case COMMAND_STRING1:
      {
         
         if(data == DOOR_CMD_STRING[mStringIndex])
         {
            ++mStringIndex;
            mMessageState = DOOR_COMMAND;
         }
         else if(data == STATUS_REQ_STRING[mStringIndex])
         {
            ++mStringIndex;
            mMessageState = STATUS_REQUEST;
         }
         else
         {
            mStringIndex = 0;
            mMessageState = COMMAND_STRING0;
         }
         break;
      }
      case DOOR_COMMAND:
      {
         if(data == DOOR_CMD_STRING[mStringIndex])
         {
            ++mStringIndex;
         }
         else
         {
            mStringIndex = 0;
            mMessageState = COMMAND_STRING0;
         }
         
         if(mStringIndex == sizeof(DOOR_CMD_STRING))
         {
            HandleDoorCmd();
            mStringIndex = 0;
            mMessageState = COMMAND_STRING0;
         }
         break;
      }
      case STATUS_REQUEST:
      {
         if(data == STATUS_REQ_STRING[mStringIndex])
         {
            ++mStringIndex;
         }
         else
         {
            mStringIndex = 0;
            mMessageState = COMMAND_STRING0;
         }
         
         if(mStringIndex == sizeof(STATUS_REQ_STRING))
         {
            ret_status = HandleStatusReq();
            mStringIndex = 0;
            mMessageState = COMMAND_STRING0;
         }
         break;
      }
      default:
      {
         //reset state
         mStringIndex = 0;
         mMessageState = COMMAND_STRING0;
         break;
      }
   }
   return ret_status;
} 

static void HandleDoorCmd()
{
   
   //trigger specific GPIO
   P1OUT |= 0x01;   //Switch relay
   delay_loop();
   P1OUT &= ~0x01;   //Stop relay
   //Send message back
}

static int HandleStatusReq()
{
   //Send back the status of the garage door
   if((P1IN & GARAGE_SWITCH_PIN) > 0)
   {
      return RET_STATUS_OPEN;
   }
   else
   {
      return RET_STATUS_CLOSED;
   }
}

static void delay_loop()
{
   uint16_t i = 0;
   while(i < 65535){ i++; asm("");}
}
